package com.hb.trade.server.center.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.Attachment;
import com.hb.core.pojo.center.sys.entity.FileRecord;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.trade.server.center.sys.service.FileRecordService;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

/**
 * 系统文件信息记录表 前端控制器
 *
 * @author zhaojk
 * @since 2022-02-07
 */
@RestController
public class FileRecordController extends MPBaseController<FileRecord, FileRecordService> {

    public FileRecordController(FileRecordService service) {
        super(service);
    }

    /**
     * 通过 dataTable 和 dataId 获取文件
     * 该方法会先判断硬盘上有没有物理文件
     * 如果没有, 再下载远程文件
     *
     * @return
     */
    @PostMapping("/fileRecord/getFile")
    public Message<FileRecord> getFile(FileRecord fileRecord) {
        QueryWrapper<FileRecord> wrapper = FileRecord.wrapper();
        wrapper.eq("data_table", fileRecord.getDataTable())
                .eq("data_id", fileRecord.getDataId()).orderByDesc("update_time").last("limit 1");
        FileRecord one = service.getOne(wrapper);
        if (one == null) {
            return MsgUtil.fail("文件数据记录不存在");
        }

        Attachment attachment = BeanUtil.copyProperties(one, Attachment.class);
        File thisFile = attachment.getThisFile();
        if (thisFile == null) {
            return MsgUtil.fail("获取文件失败(本地文件不存在, 远程文件也无法下载)");
        }

        return MsgUtil.success(one);
    }

    /**
    * Description: 保存文件
    * @author: fengbin
    * @date: 2022/3/3 12:19
    * @param fileRecord
     @return: org.fzzn.core.model.msg.Message<boolean>
    */
    @PostMapping("/fileRecord/saveFile")
    public Message<Boolean> saveFile(@RequestBody FileRecord fileRecord) {
        boolean save = false;
        // 先查询fileName 是否存在
        QueryWrapper<FileRecord> wrapper = FileRecord.wrapper();
        wrapper.eq("file_name", fileRecord.getFileName()).last("limit 1");
        FileRecord one = service.getOne(wrapper);
        if (null != one && null != one.getId()) {
            fileRecord.setId(one.getId());
            save = service.updateById(fileRecord);
        } else {
            save = service.save(fileRecord);
        }
        return save ? MsgUtil.success() : MsgUtil.fail("保存文件失败");
    }
}
